package com.wch.clientdemo.module.base.adapters;

import java.lang.reflect.Field;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.wch.clientdemo.R;
import com.wch.clientdemo.module.base.adapters.base.CustomBaseAdapter;
import com.wch.clientdemo.module.base.config.MenuModule;

/**
 * 
 * @author WanChengHe
 * @Date 20181113
 * 主页适配器
 *
 */
public class HomeFragmentAdapter extends CustomBaseAdapter<MenuModule>{

	private Activity context;

	public HomeFragmentAdapter(Activity context) {
		this.context = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		MenuModule menu = (MenuModule) getItem(position);
		ViewHolder holder = null;
		if(convertView == null){
			holder = new ViewHolder();
			convertView = View.inflate(context, R.layout.grid_item_home_fragment, null);			
			holder.iv = (ImageView) convertView.findViewById(R.id.iv);
			holder.tv = (TextView) convertView.findViewById(R.id.txtItem);
			convertView.setTag(holder);			
		}else{
			holder = (ViewHolder) convertView.getTag();
		}
		
		//添加模块名称
	/*	if(!("".equals(menu.name) || null == menu.name)){
			holder.tv.setText(menu.name);
		}*/
		if(!TextUtils.isEmpty(menu.name)){
			holder.tv.setText(menu.name);
		}
		
		Drawable drawable = getDrawable(menu.icon);
		
		if(null != drawable){
			holder.iv.setImageDrawable(drawable);
		}
		
		return convertView;
	}
	
	/**
	 * 获取模块图片
	 * @param icon
	 * @return
	 */
	 private Drawable getDrawable(String icon) {
		if(null == icon){
			return null;
		}
		
		//分析传入的图片信息，如果是进制，则将字符串转换为16进制文件即可，如果不是进制文件，是图片名，则通过反射找到相应文件
		//在R文件里面都存存储对应进制信息的，如R文件下drawable下public static final int ic_launcher=0x7f020001;，具体可以参看R文件
		try {
			if(icon.startsWith("0x")){          //可查看在线进制转换
				int r = Integer.parseInt(icon.substring(2), 16);
				return getDrawableId(r);
			}else{
				Field field = R.drawable.class.getField(icon);
				Object object = field.get(null);
				if (object instanceof Integer) {      //instanceof 某一个对象是否是一个具体类的实例
					return getDrawableId((Integer)object);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	 
	private Drawable getDrawableId(int r) {
		Drawable drawable = context.getResources().getDrawable(r);
		return drawable;
	}


	static class ViewHolder{
		 
		 ImageView iv;
		 TextView tv;
	 }
	 
	
}
